import type { FormInstance } from "element-plus";
import type { Reactive, Ref } from "vue";
import { reactive, ref } from "vue";

export interface UseBaseForm<FormData> {
    /** 表单引用 */
    formRef: Ref<FormInstance | null>;
    /** 提交加载状态 */
    submitLoading: Ref<boolean>;
    /** 表单数据 */
    formData: Reactive<FormData>;
    /** 重置表单 */
    resetForm: () => void;
}

export function useBaseForm<FormData extends Record<keyof any, any>>(getInitFormData: () => FormData): UseBaseForm<FormData> {
    /** 表单引用 */
    const formRef = ref<FormInstance | null>(null);
    /** 提交加载状态 */
    const submitLoading = ref(false);
    /** 表单数据 */
    const formData = reactive<FormData>({ ...getInitFormData() });

    /** 重置表单 */
    function resetForm(): void {
        Object.keys(formData).forEach((key) => {
            // @ts-ignore
            formData[key] = getInitFormData()[key];
        });
        formRef.value?.clearValidate();
    }

    return {
        formRef,
        submitLoading,
        formData,
        resetForm,
    };
}
